package com.wangrui.provider.service.impl;

import com.wangrui.provider.entity.Product;
import com.wangrui.provider.service.ProductService;
import com.wangrui.inventory.ProductStoreService;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;

@DubboService
public class ProductStoreServiceImpl implements ProductStoreService {
    private ProductService productService;
    @Autowired
    public ProductStoreServiceImpl(ProductService productService) {
        this.productService = productService;
    }
    @GlobalTransactional
    @Override
    public void reduceStore(Long productId,Integer num) {
        Product product = productService.getById(productId);
        if(product != null){
            product.setStoreNum(product.getStoreNum() - num);
        }
        productService.updateById(product);
        try {
            //这里设置睡眠，是为了观察数据库的变化，在此期间，consumer和provider的本地事务都提交了，undo_log表也有数据，consumer抛异常后，数据又从undo_log恢复到业务表
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if(productId == 1){
            throw new RuntimeException("provider exception");
        }
    }

    @Override
    public BigDecimal getProductPrice(Long productId) {
        Product product = productService.getById(productId);
        if(product != null){
            return product.getPrice();
        }
        return null;
    }
}
